
const { onEmit } = require('../../baseService/broadService/processor/broadcastProcessor');
const { asyncTopicConstants } = require('../../../common/constans/asyncTopicContans')
const EnvContext = require('../../../common/context/EnvContext');
const { envConst } = require('../../../common/constans/envConstans');
const fileUtil = require('../../../common/utils/fileUtil')
const { createView } = require('../../winService/baseWinService/createWebView')
const path = require('path')
const { setHeight } = require('../../winService/baseWinService/setHeight')

exports.doRunFusionPlugin = function (request) {
    /*
       1. 获取该fusion插件的preload
       2. 覆盖主渲染进程的view的preload
       */
    const preloadPath = getPreloadPath(request)
    const htmPath = getHtmPath(request)
    const pluginId = request.plugin.cmdInfo.pluginInfo.pluginId
    setHeight(600)
    switchMainPreload(preloadPath, htmPath, pluginId, () => {
        broadcastFeatureCode({ payload: request, htmPath: htmPath })
    })
}


function broadcastFeatureCode(request) {
    const theWin = EnvContext.getInstance().getMainWin()
    onEmit(asyncTopicConstants.onTriggerForFusionPlugin, request, theWin)
}

function getPreloadPath(request) {
    const pluginId = request.plugin.cmdInfo.pluginInfo.pluginId
    let preloadPath = ""
    if (envConst.dev()) {
        preloadPath = request.plugin.cmdInfo.pluginInfo.pluginInfo.development.preload
        if (!preloadPath.startsWith("/")) {
            preloadPath = path.join(fileUtil.getPluginPath(), pluginId, preloadPath)
        }
    } else {
        preloadPath = request.plugin.cmdInfo.pluginInfo.pluginInfo.preload
        if (!preloadPath.startsWith("/")) {
            preloadPath = path.join(fileUtil.getPluginPath(), pluginId, preloadPath)
        }
    }
    return preloadPath
}

function switchMainPreload(preloadPath, htmPath, pluginId, callback) {
    const mainWindow = EnvContext.getInstance().getMainWin()
    createView(mainWindow, preloadPath, htmPath, pluginId, 600, callback)
}


function getHtmPath(request) {
    const pluginId = request.plugin.cmdInfo.pluginInfo.pluginId
    let htmPath
    if (envConst.dev()) {
        htmPath = request.plugin.cmdInfo.pluginInfo.pluginInfo.development.main
        if (!htmPath.startsWith("http")) {
            htmPath = path.join(fileUtil.getPluginPath(), pluginId, htmPath)
        }
    } else {
        htmPath = request.plugin.cmdInfo.pluginInfo.pluginInfo.main
        if (!htmPath.startsWith("/")) {
            htmPath = path.join(fileUtil.getPluginPath(), pluginId, htmPath)
        }
    }

    return htmPath
}
